package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import com.itheima.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    UserService userService;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    AddressBookService addressBookService;

    @Autowired
    ShoppingCartService shoppingCartService;

    /**
     * 提交订单
     * @param orders
     */
    @Override
    @Transactional
    public void submit(Orders orders) {
        Long uerId = BaseContext.getId();

        long number = IdWorker.getId();

        AtomicInteger amount=new AtomicInteger(0);
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setOrderId(number);
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper
                =new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId,uerId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(new Function<ShoppingCart, OrderDetail>() {
            @Override
            public OrderDetail apply(ShoppingCart shoppingCart) {
                AtomicInteger detailAmount=new AtomicInteger(0);
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderId(number);
                orderDetail.setDishId(shoppingCart.getDishId());
                orderDetail.setSetmealId(shoppingCart.getSetmealId());
                orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
                orderDetail.setNumber(shoppingCart.getNumber());
                orderDetail.setImage(shoppingCart.getImage());
                amount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
                detailAmount.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
                orderDetail.setAmount(new BigDecimal(detailAmount.get()));
                return orderDetail;
            }
        }).collect(Collectors.toList());

        //向订单明细表中插入数据
        orderDetailService.saveBatch(orderDetailList);

        orders.setId(number);
        orders.setNumber(String.valueOf(number));
        orders.setStatus(1);
        orders.setUserId(uerId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(1);
        User user = userService.getById(uerId);
        String phone = user.getPhone();
        orders.setPhone(phone);
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook==null){
            throw new  CustomException("地址信息有误不能下单");
        }
        orders.setAddress(
                (addressBook.getProvinceName()==null?"":addressBook.getProvinceName())+
                        (addressBook.getCityName()==null?"":addressBook.getCityName())+
                        (addressBook.getDistrictName()==null?"":addressBook.getDistrictName())
        );

        orders.setAmount(new BigDecimal(amount.get()));

        //像订单表中插入数据
        this.save(orders);

        //清空购物车数据
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

    }
}